package com.ds.infrastructure.audit.client.annotation;

import com.alibaba.fastjson.JSON;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * 作用：
 *
 * @author WeiShaoying
 * @date 2020/7/27
 */
@Slf4j
@Data
public class AuditValidator implements ConstraintValidator<KbaAudit, Object> {


    private String shopId;

    // 业务名称
    private String bizName;

    //业务数据的唯一标识，可选
    private String behaviorId;

    // 行为
    private String action;

    // 行为详情
    private String actionDetail;

    // 重要级别
    private Integer priority;

    // 用户Id
    private String userId;

    // 扩展信息json
    private String extra;

    // 创建时间戳
    private Long createTime;

    @Override
    public void initialize(KbaAudit constraintAnnotation) {
        bizName = constraintAnnotation.bizName();
        userId = constraintAnnotation.userId();
        action = constraintAnnotation.action();
        priority = constraintAnnotation.priority();
        log.info("ConstraintValidator initialize: {},{},{}",  bizName, userId, action);
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext constraintValidatorContext) {
        if (StringUtils.isBlank(bizName) || StringUtils.isBlank(userId) || StringUtils.isBlank(action)) {
            //禁止默认消息返回
            constraintValidatorContext.disableDefaultConstraintViolation();
            //自定义返回消息
            constraintValidatorContext.buildConstraintViolationWithTemplate("bizName,userId,action不能为空").addConstraintViolation();
            return false;
        }
        if (StringUtils.isNotBlank(extra)) {
            try {
                JSON.parseObject(extra);
            } catch (Exception e) {
                constraintValidatorContext.disableDefaultConstraintViolation();
                //自定义返回消息
                constraintValidatorContext.buildConstraintViolationWithTemplate("参数extra格式错误,正确的格式为JSON").addConstraintViolation();
                return false;
            }
        }
        return true;
    }
}
